package com.lhd.qd.common.util;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 通用工具类
 */
@Component
public class CommonUtils {

    public static final String REGEX_IPV4 = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "").toLowerCase();
    }

    public static long ip2Long(String ipStr) {
        if (!isIpv4(ipStr)) {
            return 0L;
        }
        String[] ipNums = ipStr.split("\\.");
        return (Long.parseLong(ipNums[0]) << 24)
                + (Long.parseLong(ipNums[1]) << 16)
                + (Long.parseLong(ipNums[2]) << 8)
                + (Long.parseLong(ipNums[3]));
    }

    public static boolean isIpv4(String ip) {
        if (ip == null || ip.length() == 0) {
            return false;
        }
        return Pattern.matches(REGEX_IPV4, ip);
    }

    public static String long2Ip(long ipLongValue) {
        return (ipLongValue >>> 24) + "." +
                ((ipLongValue & 0X00FFFFFF) >>> 16) + "." +
                ((ipLongValue & 0X0000FFFF) >>> 8) + "." +
                (ipLongValue & 0X000000FF);
    }

    public static long getRequestLongIp(HttpServletRequest request) {
        String ip = getRequestIp(request);
        return isIpv4(ip) ? ip2Long(ip) : 0L;
    }

    public static String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
